import axios from "axios";
import { notification, message } from "ant-design-vue";
import store from "../../store";
import defaultSetting from "./defaultSetting";
import utils from "./utils";
// import { useRoute, useRouter } from "vue-router";
import router from "@/router/index.js";
import { Modal } from "ant-design-vue";

let showMsg = true;

let BASE_URL = defaultSetting.requestDomain;
let flag = false;

let isModal;
const showModal = (msg) => {
  if (isModal) return;
  isModal = Modal.confirm({
    title: "提示",
    content: msg || "当前账号角色已被禁用",
    okText: "我知道了",
    keyboard: false,
    closable: false,
    cancelButtonProps: { style: { display: "none" } }, // 隐藏取消按钮
    onOk() {
      isModal.destroy();
      isModal = null;
      utils.clearUserToken();
      store.dispatch("Logout");
      // router.push({
      //   name: "Home",
      // });
    },
    onCancel() {
      isModal.destroy();
      isModal = null;
      utils.clearUserToken();
      store.dispatch("Logout");
    },
  });
};

if (process.env.NODE_ENV === "development") {
  BASE_URL = BASE_URL + "/api";
}
// 创建axios实例
const service = axios.create({
  // API 请求的默认前缀
  baseURL: BASE_URL,
  // 请求超时时间
  timeout: 30000,
});

/**
 * @description: 请求异常处理
 * @param {*} data 返回数据
 * @return {*}
 * @code    返回的状态码对应的类型:
 *          *1000 正常响应
 *          *1001 业务逻辑错误
 *          *1002 登录超时
 *          *1005 前端错误(缺少参数等)
 */
export const errorHandler = (response) => {
  // 代码错误提示
  const errorNotification = (tip, errorLevel) => {
    if (!showMsg) {
      setTimeout(() => {
        showMsg = true;
      }, 1000);
      return;
    }

    return notification[errorLevel]({
      message: errorLevel == "warning" ? "警告" : "错误",
      description: tip,
    });
  };
  // debugger
  if (response.data) {
    const { config } = response;
    const { code, msg, errorLevel } = response.data;
    // debugger
    const token = utils.getUserToken();
    if (
      (config && config.data && config.data.hideErrMsg) ||
      (config && config.params && config.params.hideErrMsg)
    ) {
      return Promise.reject(response.data);
    } else {
      switch (code) {
        case 1001:
          errorNotification(
            msg || "接口响应错误,请检查逻辑代码等!",
            errorLevel
          );
          showMsg = false;
          break;
        case 1005:
          errorNotification(
            msg || "前端请求错误,请检查请求参数等!",
            errorLevel
          );
          showMsg = false;
          break;
        case 1002:
          if (token) {
            message.warning("登录超时,请重新登录~");
          }
          break;
        case 1003:
          errorNotification(msg || "权限错误!", errorLevel);
          showMsg = false;
          break;
        case 3601:
          errorNotification(msg || "您没有能量币或套餐已到期啦,请购买后使用", errorLevel);
          showMsg = false;
          return response
          break;
        case 3602:
          if (utils.isLogin()) {
            utils.clearUserToken();
            console.log("登录过期 -- 有token");

            errorNotification("登录状态已过期，请重新登录", errorLevel);
            // debugger
            // 清除token,进入登录页面
            store.dispatch("Logout").then(() => {
              // location.reload();
            });
            return Promise.reject(response.data);
          } else {
            console.log("登录过期 -- 无无token");
            errorNotification("请登录", errorLevel);
            return Promise.reject(response.data);
          }

          // 清除token,进入登录页面
          // store.dispatch("Logout").then(() => {
          //   if (window.__MICRO_APP_ENVIRONMENT__) {
          //     window.rawWindow.location.reload();
          //   } else {
          //     location.reload();
          //   }
          // });
          break;
        case 3603:
          showModal(msg);
          break;
        default:
          return Promise.reject(response.data);
      }
    }
  } else {
    errorNotification("哎呀，网络请求超时，请稍后再试", "warning");
    return Promise.reject(response);
  }
};

// request拦截器
service.interceptors.request.use((config) => {
  const user_token = utils.getUserToken();
  if (user_token) {
    config.headers["user-token"] = config?.params?.user_token
      ? config?.params?.user_token
      : config?.data?.user_token
      ? config?.data?.user_token
      : user_token;
  }
  if (config.params) {
    config.params.org_id = utils.getOrgId();
    config.params.user_token = utils.getToken();
    config.params.cur_env = utils.isMobile()
      ? "h5"
      : import.meta.env.ELECTRON
      ? "desktop"
      : "pc";
    config.params.team_id = utils.getCurrentTeam();
  }
  if (config.data) {
    config.data.org_id = utils.getOrgId();
    config.data.user_token = utils.getToken();
    config.data.cur_env = utils.isMobile()
      ? "h5"
      : import.meta.env.ELECTRON
      ? "desktop"
      : "pc";
    config.data.team_id = utils.getCurrentTeam();
  }

  return config;
}, errorHandler);

// response拦截器
service.interceptors.response.use((response) => {
  if (response.data) {
    const { code } = response.data;
    if (code === 1000) {
      return response.data;
    } else if (code == 1001) {
      notification.warn({ message: response.data.msg, duration: 2 });
      let org_id = utils.getOrgId();
      // if(!org_id) {
      //   store.dispatch("Logout").then(() => {});
      //   location.reload();
      // }
      
      return response;
    }
    if (response.request.responseType == "blob") {
      // let fileNameArr =
      //   response.headers["content-disposition"].split("filename*=UTF-8''");
      let fileName = "";
      // if (fileNameArr.length > 1) {
      //   fileName = fileNameArr[1];
      //   fileName = decodeURIComponent(fileName);
      // }
      return { data: response.data, fileName };
    }
  }
  return errorHandler(response);
}, errorHandler);

const request = {
  BASE_URL,
  // get请求 server微服务 url 请求地址
  get(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .get(url, {
          params,
        })
        .then((res) => {
          // if (url == '/work_ai/config') {
          //   res.data.list.only_digital_human = true
          // }
          // console.log(res,url,'请求结果!123123123');
          
          if (params.needMsg) {
            resolve(res);
          }
          if (!!res && !!res?.data) {
            resolve(res.data);
          } else {
            resolve(res);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  //   post请求
  post(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .post(url, params)
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          if (!!res && !!res?.data) {
            resolve(res.data);
          } else {
            resolve(res);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  //  put请求
  put(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .put(url, params)
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          if (!!res && !!res?.data) {
            resolve(res.data);
          } else {
            resolve(res);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // delete请求
  del(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .delete(url, { data: params })
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          if (!!res && !!res?.data) {
            resolve(res.data);
          } else {
            resolve(res);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // patch请求
  patch(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .patch(url, params)
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  upload(server, url, params = {}, config = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      const data = new FormData();

      for (var key in params) {
        data.append(key, params[key]);
      }
      service
        .post(url, data, config)
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // 下载downLoad
  downLoad(server, url, params = {}, contentType = "") {
    return new Promise((resolve, reject) => {
      url = server + url;

      service
        .get(url, {
          params,
          responseType: "blob",
          headers: {
            "content-type":
              contentType ||
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          },
          timeout: 600000,
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          console.log(err, "err");
          reject(err);
        });
    });
  },

  // 分片下载函数
  newDownload: (url, params = {}, headers = {}, responseType = "blob") => {
    return new Promise((resolve, reject) => {
      service
        .get(url, {
          params,
          headers,
          responseType,
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          console.error("Download error:", err);
          reject(err);
        });
    });
  },
};

export default request;
